package com.mylater.nace.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * The NamedThreadFactory represents InternalThreadFactory
 *
 * @author fengjiachun
 * @version $Id$
 */
public class NaceThreadFactory implements ThreadFactory {

    private static final Logger LOG = LoggerFactory.getLogger(NaceThreadFactory.class);

    private static final AtomicInteger POOL_SEQ = new AtomicInteger(1);

    private final AtomicInteger mThreadNum = new AtomicInteger(1);

    private final String mPrefix;

    private final boolean mDaemo;

    private final ThreadGroup mGroup;

    public NaceThreadFactory() {
        this("pool-" + POOL_SEQ.getAndIncrement(), false);
    }

    public NaceThreadFactory(String prefix) {
        this(prefix, false);
    }

    public NaceThreadFactory(String prefix, boolean daemo) {
        this.mPrefix = prefix + "-thread-";
        this.mDaemo = daemo;
        SecurityManager s = System.getSecurityManager();
        this.mGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
    }

    @Override
    public Thread newThread(Runnable r) {
        String name = this.mPrefix + this.mThreadNum.getAndIncrement();
        Thread thread = new Thread(this.mGroup, r, name, 0);
        thread.setDaemon(this.mDaemo);
        if (LOG.isInfoEnabled()) {
            LOG.info("new thread created : {}, group active count : {}", name, this.mGroup.activeCount());
        }
        return thread;
    }

    public ThreadGroup getThreadGroup() {
        return this.mGroup;
    }

}
